package com.upcode.weighing.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.upcode.weighing.common.constant.BillConstants;
import com.upcode.weighing.common.enums.HttpStatus;
import com.upcode.weighing.domain.*;
import com.upcode.weighing.exception.ExcelException;
import com.upcode.weighing.exception.SysOrgException;
import com.upcode.weighing.mapper.SysOrganizationMapper;
import com.upcode.weighing.mapper.SysUserMapper;
import com.upcode.weighing.mapper.SysUserRoleMapper;
import com.upcode.weighing.service.SysOrganizationService;
import com.upcode.weighing.service.SysRoleService;
import com.upcode.weighing.service.SysUserRoleService;
import com.upcode.weighing.service.SysUserService;
import com.upcode.weighing.util.ImportRedisKeyContants;
import com.upcode.weighing.util.SecurityUtils;
import com.upcode.weighing.util.SensitiveInfoUtils;
import com.upcode.weighing.vo.add.SysUserAddVo;
import com.upcode.weighing.vo.del.BaseDelVo;
import com.upcode.weighing.vo.edit.SysUserEditVo;
import com.upcode.weighing.vo.req.PageReqVo;
import com.upcode.weighing.vo.req.excel.UserDetialImportExcelReqVo;
import com.upcode.weighing.vo.req.org.OrgMigrationReqVo;
import com.upcode.weighing.vo.req.pc.SysUserAuthReqVo;
import com.upcode.weighing.vo.req.pc.SysUserDelReqVo;
import com.upcode.weighing.vo.req.pc.SysUserReqVo;
import com.upcode.weighing.vo.req.pc.SysUserUpdatePwdVo;
import com.upcode.weighing.vo.resp.PageRespVo;
import com.upcode.weighing.vo.resp.pc.SysUserDetail;
import com.upcode.weighing.vo.resp.pc.SysUserRespVo;
import com.upcode.weighing.vo.resp.user.UserImportErrorRespVo;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

import static com.upcode.weighing.common.constant.BillConstants.CHU_SHI_HUA_PSW;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author alex
 * @since 2019-04-10
 */
@Service
@Transactional
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {
    private static final Logger logger = LoggerFactory.getLogger(SysUserServiceImpl.class);

    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private SysOrganizationService organizationService;

    @Autowired
    private SysOrganizationMapper sysOrganizationMapper;

    @Autowired
    private SysRoleService roleService;

    @Autowired
    private SysUserRoleService sysUserRoleService;
    
    @Override
    public SysUserDetail getUserDetailById(long userId) {
        SysUser sysUser = sysUserMapper.selectById(userId);
        SysUserDetail sysUserDetail = new SysUserDetail();
       if(sysUser != null){
           BeanUtils.copyProperties(sysUser, sysUserDetail);
       }
        return sysUserDetail;
    }

    @Override
    public Integer checkLoginId(String loginId) {
        Integer i = sysUserMapper.checkLoginId(loginId);
        return i;
    }

    @Override
    public IPage<SysUserRespVo> selectByList(PageReqVo<SysUserReqVo> vo) {
        Page<SysUserReqVo> pageInfo = new Page<>(vo.getPage().getCurrentPage(), vo.getPage().getPageSize());

        SysUserReqVo params = vo.getParams();



        IPage<SysUserRespVo> page = sysUserMapper.selectPageList(pageInfo, params);
        if (null != page && null != page.getRecords() && page.getRecords().size() > 0) {
            for (SysUserRespVo user : page.getRecords()) {
                // 手机号 身份证脱敏
                user.setTel(SensitiveInfoUtils.sensitiveTel(user.getTel()));
                user.setIdNum(SensitiveInfoUtils.sensitiveIdCard(user.getIdNum()));

                String redisKeyTen = "locking:ten:"+user.getLoginName()+"";
                String jsonStrTen = stringRedisTemplate.boundValueOps(redisKeyTen).get();
                Integer lockingNumTen = StringUtils.isBlank(jsonStrTen)?0:Integer.valueOf(jsonStrTen);
                if(lockingNumTen >=10){
                    user.setIsLock(true);
                    continue;
                }
                String redisKeyThree = "locking:three:"+user.getLoginName()+"";
                String jsonStrThree = stringRedisTemplate.boundValueOps(redisKeyThree).get();
                Integer lockingNumThree = StringUtils.isBlank(jsonStrThree)?0:Integer.valueOf(jsonStrThree);
                if(lockingNumThree >=3){
                    user.setIsLock(true);
                    continue;
                }
            }
        }
        return page;
    }

    @Override
    public List<SysUserRespVo> selectByList(SysUserReqVo params) {


        return sysUserMapper.selectPageList(params);
    }

    @Override
    public boolean saveInfo(SysUserAddVo vo) {
        boolean ok=false;
        //添加用户
        SysUser u=new SysUser();
        u.setId(IdWorker.getId());//用户ID
        u.setLoginName(vo.getLoginName());//登录名
        String defaultPwd="User@123";
        u.setPwd(new BCryptPasswordEncoder().encode(defaultPwd));//密码(加密)
        u.setName(vo.getName());//姓名
        u.setTelephone(vo.getPhone());//手机号
//        u.setAgencyType(vo.getOrgId1().toString());//部门ID
//        u.setAgencyId(vo.getOrgId2().toString());//岗位ID
        u.setSex(0);//性别 默认为 0男
        u.setStatus(BillConstants.ACCOUNT_SUBSCRIBER_BEHAVIOUR_START);//默认可用 1可用
        u.setCreateTime(LocalDateTime.now());//创建时间
        u.setUpdateTime(LocalDateTime.now());//修改时间
        int a=sysUserMapper.insert(u);
        //添加用户及对应角色
        SysUserRole sysUserRole=new SysUserRole();
        sysUserRole.setId(IdWorker.getId());//用户-角色:ID
        sysUserRole.setUserId(u.getId());//用户-角色:用户ID
        sysUserRole.setRoleId(vo.getRoleId());//用户-角色:角色ID
        int b=sysUserRoleService.addUserRole(sysUserRole);
        if(a>0&&b>0){
            ok=true;
        }
        return ok;

    }

    @Override
    public SysUserEditVo selectById(Long id) {
        SysUserEditVo sysUser = sysUserMapper.getById(id);
        sysUser.setAgencyId(getUserDetailById(id).getAgencyId());
        return sysUser;
    }

    @Override
    public boolean updateById(SysUserEditVo vo, String opType,Integer disableUserDaysNoUpPwd) {

        LocalDateTime now = LocalDateTime.now();
        SysUser user = new SysUser();
        BeanUtils.copyProperties(vo, user);
        user.setId(new Long(vo.getId()));
        if ("4".equals(opType)) {
            //获取用户密码
            String passWord = new BCryptPasswordEncoder().encode(vo.getPwd());
            user.setPwd(passWord);
        }else if("1".equals(opType)){
            user.setStatus(0);
        }else if("2".equals(opType)){
            user.setStatus(-1);
        }else if("3".equals(opType)){
            user.setStatus(1);
            user.setDefaultPasswordLoginNum(0);
            user.setLastUpPasswordTime(LocalDateTime.now().plusDays(0-disableUserDaysNoUpPwd-5));
        }
        user.setUpdateTime(now);
        int a = sysUserMapper.updateById(user);
        if (a < 0) {
            System.out.println("user=" + a);
            throw new RuntimeException("用户信息修改失败!");
        }



        if ("0".equals(opType)) {
            //用户角色表

            SysUserRole userRole = new SysUserRole();
            QueryWrapper<SysUserRole> qw = new QueryWrapper<>();
            qw.eq("user_id", user.getId());

            if (userRoleMapper.delete(qw) < 1) {
                throw new RuntimeException("修改角色失败!");
            }
            userRole.setId(IdWorker.getId());
            userRole.setRoleId(new Long(vo.getRoleId()));
            userRole.setUserId(user.getId());
            int c = userRoleMapper.insert(userRole);
            if (c < 0) {
                System.out.println("userRole=" + c);
                throw new RuntimeException("用户信息修改失败!");
            }
        }
        return true;
    }
    @Override
    public int updateByPWD(SysUser vo) throws RuntimeException{
        vo.setLastUpPasswordTime(LocalDateTime.now());
        vo.setDefaultPasswordLoginNum(0);
        return sysUserMapper.updateById(vo);
    }

    @Override
    public boolean updatePwd(SysUserUpdatePwdVo vo) {
        String newPassword = vo.getNewPassword();
        String repPassword = vo.getRepPassword();

    	if(!StringUtils.equals(newPassword,repPassword)){
            throw new RuntimeException("两次输入密码不一致");
        }
        SysUser sysUser = getById(vo.getId());
//        boolean checkOld = new BCryptPasswordEncoder().matches(vo.getOldPassword(),sysUser.getPwd());
//        if(!checkOld){
//            throw new RuntimeException("旧密码输入不正确");
//        }
        boolean checkNew = new BCryptPasswordEncoder().matches(newPassword,sysUser.getPwd());
        if(checkNew){
            throw new RuntimeException("旧密码和新密码相同");
        }
        sysUser.setPwd(new BCryptPasswordEncoder().encode(newPassword));
        sysUser.setLastUpPasswordTime(LocalDateTime.now());
        sysUser.setDefaultPasswordLoginNum(0);
        if (StringUtils.isNotEmpty(vo.getAvatar())){
            sysUser.setAvatar(vo.getAvatar());
        }
        return updateById(sysUser);
    }

    /**
     * 重置密码
     * @param vo
     * @return
     */
    @Override
    public boolean resetUserPwd(SysUser vo) {
        Integer updateNum = sysUserMapper.resetUserPwd(vo);
        return null != updateNum && updateNum.intValue() == 1;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void batchDelete(SysUserDelReqVo reqVo, String opType, Integer disableUserDaysNoUpPwd) {
        reqVo.getIds().forEach(item -> {
            SysUserEditVo editVO= new SysUserEditVo();
            editVO.setId(item);
            updateById(editVO, opType, disableUserDaysNoUpPwd);
        });
    }

    @Override
    public XSSFWorkbook exportUserList(File file, SysUserReqVo params) throws Exception {
        // 获取数据
        if (StringUtils.isNotBlank(params.getIdNum())) {
            params.setIdNum(params.getIdNum().trim());
        }
        if (StringUtils.isNotBlank(params.getOrgName())) {
            params.setOrgName(params.getOrgName().trim());
        }
        if (StringUtils.isNotBlank(params.getTel())) {
            params.setTel(params.getTel().trim());
        }
        if (StringUtils.isNotBlank(params.getId())) {
            params.setId(params.getId().trim());
        }


        List<SysUserRespVo> exportData = sysUserMapper.selectPageList(params);

        if (CollectionUtils.isEmpty(exportData)) {
            throw new SysOrgException("未查询到导出数据");
        }
        // EXCEL构建
        XSSFWorkbook xssfWorkbook;
        FileInputStream is = new FileInputStream(file);
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        final XSSFWorkbook workbook = new XSSFWorkbook(is);
        xssfWorkbook = workbook;
        XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(0);
        XSSFRow row;
        // 将数据插入到excel中
        int rowNum = 0;
        int columnIndex = 0;
        for (SysUserRespVo info : exportData) {
            row = xssfSheet.createRow(++rowNum);

            row.createCell(columnIndex++).setCellValue(rowNum);
            row.createCell(columnIndex++).setCellValue(info.getName());
            row.createCell(columnIndex++).setCellValue(info.getRoleName());
            row.createCell(columnIndex++).setCellValue(info.getTel());
            row.createCell(columnIndex++).setCellValue(info.getIdNum());
            row.createCell(columnIndex++).setCellValue(info.getOrgName());
            row.createCell(columnIndex++).setCellValue(info.getLoginName());
            row.createCell(columnIndex++).setCellValue(Objects.nonNull(info.getCreateTime()) ? dtf.format(info.getCreateTime()) : null);
            if (info.getStatus() == 1) {
                row.createCell(columnIndex++).setCellValue("启用");
            }
            if (info.getStatus() == 0) {
                row.createCell(columnIndex++).setCellValue("禁用");
            }
//            row.createCell(columnIndex++).setCellValue(OrgTypeEnum.getMsg(info.getOrgType()));

            columnIndex = 0;
        }
        return xssfWorkbook;
    }


    @Override
    public String getImportDataSchedule(String orgCode) {
        String userBatchImportKey = String.format(ImportRedisKeyContants.USER_IMPORT_KEY, orgCode, SecurityUtils.getCurrentUserId());
        logger.info("用户管理导入进度查询 redisKey: {}", userBatchImportKey);
        String result = stringRedisTemplate.boundValueOps(userBatchImportKey).get();
        logger.info("用户管理导入进度查询 result: {}", result);
        if (ImportRedisKeyContants.USER_IMPORT_COMPLETE.equals(result)) {
            stringRedisTemplate.delete(userBatchImportKey);
        }
        return result;
    }

    private void checkString(String fieldName, String str, int checkLen) throws ExcelException {
        if (StringUtils.isBlank(str)) {
            throw new ExcelException(String.format("%s不能为空", fieldName));
        }

        str = str.trim();

        if (str.length() > checkLen) {
            throw new ExcelException(String.format("%s超过限定长度", fieldName));
        }
    }

    private void buildErrorMsg(UserImportErrorRespVo errorResp, String appendErrorMsg) {
        if (StringUtils.isBlank(errorResp.getErrorMsg())) {
            errorResp.setErrorMsg(appendErrorMsg);
        } else {
            errorResp.setErrorMsg(String.format("%s；%s", errorResp.getErrorMsg(), appendErrorMsg));
        }
    }

    /**
     * 获取单元格的值的字符串
     * @param cell 单元格对象
     * @return cell单元格的值的字符串
     */
    private static String getStringValue(Cell cell) {
        if (cell == null) {
            return null;
        }
        CellType cellType = cell.getCellTypeEnum();
        switch (cellType) {
            case STRING:
                return cell.getStringCellValue().trim();
            case NUMERIC:
                double value = cell.getNumericCellValue();
                return String.valueOf(Math.round(value));
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            default:
                return null;
        }
    }

    @Override
    public XSSFWorkbook buildImportTemplateDic(File file) throws Exception {
        // 数据字典模板回填
        InputStream is = new FileInputStream(file);
        XSSFWorkbook xssfWorkbook = new XSSFWorkbook(is);
        // 默认放置在sheet1中
        XSSFSheet dicSheet = xssfWorkbook.getSheetAt(1);

        // 员工性别
        List<String> sexList = Arrays.asList("男", "女");
        buildSheetDicRow(dicSheet, sexList, 0);

        // 员工角色
        List<SysRole> roleList = roleService.list();
        List<String> roleNameList = new ArrayList<>();
        roleList.forEach(item -> {
            if (!roleList.contains(item.getName())) {
                roleNameList.add(item.getName());
            }
        });
        buildSheetDicRow(dicSheet, roleNameList, 1);

        return xssfWorkbook;
    }

    private void buildSheetDicRow(XSSFSheet dicSheet, List<String> sexList, int cloumn) {
        int sexSize = sexList.size();
        for (int i = 1; i <= sexSize; i++) {
            if (dicSheet.getRow(i) != null) {
                dicSheet.getRow(i).createCell(cloumn).setCellValue(sexList.get(i - 1));
            } else {
                dicSheet.createRow(i).createCell(cloumn).setCellValue(sexList.get(i - 1));
            }
        }
    }

    @Override
    public void batchHandleLinkOrg2User(MultipartFile file) throws Exception {
        long startTime = System.currentTimeMillis();

        InputStream is = file.getInputStream();
        XSSFWorkbook xssfWorkbook = new XSSFWorkbook(is);
        XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(0);
        if (Objects.isNull(xssfSheet)) {
            throw new SysOrgException("未检测到需要导入的内容");
        }
        if (xssfSheet.getLastRowNum() > 1000) {
            throw new SysOrgException("最多只可导入1000条数据");
        }

        // 获取所有机构编码信息

        QueryWrapper<SysOrganization> orgQw = new QueryWrapper<SysOrganization>()
            .select( "org_code", "org_name")
            .eq("is_delete", 1);
        List<SysOrganization> orgList = sysOrganizationMapper.selectList(orgQw);


        // 获取所有未删除账户
        QueryWrapper<SysUser> userQw = new QueryWrapper<SysUser>()
            .select( "id", "login_name")
            .ne("status", -1);
        List<SysUser> sysUserList = sysUserMapper.selectList(userQw);
        Map<String, String> loginNameIdMap = sysUserList.stream()
            .collect(Collectors.toMap(SysUser::getLoginName, item->String.valueOf(item.getId()), (v1, v2) -> v2));

        // 校验异常信息列表
        List<UserImportErrorRespVo> errorMsgList = new ArrayList<>();

        // 预处理实体集合
        List<UserDetialImportExcelReqVo> repImportUserDetailList = new ArrayList<>();

        boolean checkFlag = true;

        int cellNum = 0;

        logger.info("用户管理导入 EXCEL sheet0 LastRowNum: {}", xssfSheet.getLastRowNum());

        for (int rowNum = 1; rowNum <= xssfSheet.getLastRowNum(); rowNum++) {
            boolean rowSave = true;

            XSSFRow xssfRow = xssfSheet.getRow(rowNum);
            if (xssfRow == null) {
                continue;
            }

            UserDetialImportExcelReqVo record = new UserDetialImportExcelReqVo();
            UserImportErrorRespVo errorResp = new UserImportErrorRespVo();

            // 序号
            String num = getStringValue(xssfRow.getCell(0));
            try {
                errorResp.setNum(num);
                checkString("序号", num, 3);
            } catch (ExcelException e) {
                checkFlag = false;
                rowSave = false;
                buildErrorMsg(errorResp, e.getMessage());
            }

            // 职工编码
            String userId = getStringValue(xssfRow.getCell(1));
            try {
                errorResp.setName(userId);
                checkString("职工编码", userId, 100);
                if (!loginNameIdMap.containsValue(userId)) {
                    throw new ExcelException("职工编码不存在!");
                }
                record.setSysUserId(Long.parseLong(userId));
            } catch (ExcelException e) {
                checkFlag = false;
                rowSave = false;
                buildErrorMsg(errorResp, e.getMessage());
            }

            // 登录账号
            String loginName = getStringValue(xssfRow.getCell(2));
            try {
                errorResp.setLoginName(loginName);
                checkString("登录账号", loginName, 100);
                if (!loginNameIdMap.containsKey(loginName)) {
                    throw new ExcelException("账号不存在!");
                }
                record.setLoginName(loginName);
//                record.setSysUserId(loginNameIdMap.get(loginName));
            } catch (ExcelException e) {
                checkFlag = false;
                rowSave = false;
                buildErrorMsg(errorResp, e.getMessage());
            }

            // 机构编码
            String orgCode = getStringValue(xssfRow.getCell(3));
            try {
                checkString("机构编码", orgCode, 100);

                record.setOrgCode(orgCode);

            } catch (ExcelException e) {
                checkFlag = false;
                rowSave = false;
                buildErrorMsg(errorResp, e.getMessage());
            }

            if (!rowSave) {
                errorMsgList.add(errorResp);
            } else {
                repImportUserDetailList.add(record);
            }
        }

        if (!checkFlag) {
            throw new SysOrgException(HttpStatus.VALIDATED_FAIL, errorMsgList);
        }

        long endTime = System.currentTimeMillis();
        logger.info("用户与机构关联批量导入耗时: {}ms", endTime - startTime);
    }

    @Transactional(noRollbackFor = SysOrgException.class)
    @Override
    public void migrateOwnOrg(OrgMigrationReqVo reqVo) {
        // 数据入库
        SysUser upUser = new SysUser();

        sysUserMapper.updateById(upUser);
    }

    @Override
    public List<SysUserRespVo> selectList(SysUserReqVo reqVo) {
        return null;
    }


    @Transactional(noRollbackFor = SysOrgException.class)
    @Override
    public void batchAuthorize(SysUserAuthReqVo reqVo) {
        // 校验角色是否正常存在
        List<SysRole> roleList = roleService.list();
        List<String> roleIdList =
            roleList.stream().map(item -> String.valueOf(item.getId())).collect(Collectors.toList());

        if (!roleIdList.contains(reqVo.getRoleId())) {
            throw new SysOrgException("所选角色信息不存在");
        }

        // 用户角色表处理
        List<String> userIdList = reqVo.getIds();
        Long roleId = Long.parseLong(reqVo.getRoleId());

        int userIdListlen = userIdList.size();

        QueryWrapper<SysUserRole> qw = new QueryWrapper<>();
        qw.in("user_id", userIdList);
        int deleteCount = userRoleMapper.delete(qw);
        logger.info("用户批量授权-> 入参:userIdListlen={}, 删除:deleteCount={}", userIdListlen, deleteCount);

        List<SysUserRole> saveRoleList = new ArrayList<>();
        userIdList.forEach(item -> {
            SysUserRole userRole = new SysUserRole();
            userRole.setId(IdWorker.getId());
            userRole.setRoleId(roleId);
            userRole.setUserId(Long.parseLong(item));
            saveRoleList.add(userRole);
        });
        sysUserRoleService.saveBatch(saveRoleList);
        logger.info("用户批量授权完成");
    }

    @Override
    public List<SysUser> queryList(SysUserReqVo reqVo) {
        return sysUserMapper.queryList(reqVo);

    }

    @Override
    public void importData(MultipartFile file, String orgCode) throws Exception {

    }
    //根据登录名获取菜单
    @Override
    public List<SysRes> getResByLoginName(String loginName) {
        List<SysRes> list=sysUserMapper.getResByLoginName(loginName);
        List<SysRes> list1=new ArrayList<SysRes>();
        for(SysRes r:list){
            if(r.getPid()==0){
                list1.add(r);
            }
        }
        for(SysRes r:list1){
            r.setChildRes(getChild(r.getId(),list));
        }
        return list1;
    }

    //获取三级菜单权限
    @Override
    public List<String> getResByParam(String loginName) {
        return sysUserMapper.getResByParam(loginName);
    }

    //超级管理员获取所有权限
    @Override
    public List<String> getAdminPer() {
        return sysUserMapper.getAdminPer();
    }

    /**
     * 查询账号管理分页列表
     */
    @Override
    public PageRespVo<SysDetail> list(PageReqVo<SysDetail> vo) {
        Page<SysDetail> pageInfo = new Page<>(vo.getPage().getCurrentPage(), vo.getPage().getPageSize());//创建分页
        PageRespVo<SysDetail> pageRespVo = new PageRespVo<>();
        IPage<SysDetail> iPage = sysUserMapper.selectAccount(pageInfo,vo.getParams());
        pageRespVo.setPage(iPage);
        for (SysDetail sd:pageRespVo.getPage().getRecords()){
            sd.setTelephone(SensitiveInfoUtils.sensitiveTel(sd.getTelephone()));
            sd.setCard(SensitiveInfoUtils.sensitiveBankCard(sd.getCard()));
        }
        return pageRespVo;
    }
    /**
     * 查询账号详情
     */
    @Override
    public SysDetail getByUserId(Long userId) {
        return sysUserMapper.getByUserId(userId);
    }
    @Override
    public boolean updateByUserId(SysEditVo user) throws RuntimeException {
        if (null==user.getId()){
            throw new RuntimeException("修改账号失败");
        }
        if (null!=user.getRoleId()){
            SysUserRole  vo = sysUserRoleService.queryByUserId(user.getId());
            if (null==vo){
                SysUserRole userRole = new SysUserRole();
                userRole.setUserId(user.getId());//用户id
                userRole.setRoleId(user.getRoleId());//角色id
                userRole.setId(IdWorker.getId());//主键id
                sysUserRoleService.save(userRole);
            }else {
                vo.setRoleId(user.getRoleId());//角色id
                vo.setUserId(user.getId());//用户id
                sysUserRoleService.saveOrUpdate(vo);
            }
        }
        SysUser u = new SysUser();
        BeanUtils.copyProperties(user,u);
        boolean contains1 = u.getTelephone().contains("*");
        if (contains1){u.setTelephone("");}
        u.setUpdateTime(LocalDateTime.now());//修改时间
        int i = sysUserMapper.updateByUserId(u);
        if (i>0){
            return true;
        }
        return false;
    }
    /**
     *初始化密码
     */
    @Override
    public boolean initializePWD(SysEditVo user) throws RuntimeException {
        if (null==user.getId()){
            throw new RuntimeException("初始化密码失败");
        }
        SysUser u = new SysUser();
        u.setId(user.getId());//用户id
        u.setPwd(new BCryptPasswordEncoder().encode(CHU_SHI_HUA_PSW));//初始化密码为  111111
        u.setLastUpPasswordTime(LocalDateTime.now());//最后更改密码时间
        u.setUpdateTime(LocalDateTime.now());//最后更新时间
        return updateById(u);
    }
    /**
     *冻结账号
     */
    @Override
    public boolean freeze(SysEditVo user)throws RuntimeException {
        if (null==user.getId()){
            throw new RuntimeException("禁用账号失败");
        }
        SysUser byId = getById(user.getId());//查询远账号是否被删除
        if (BillConstants.ACCOUNT_SUBSCRIBER_BEHAVIOUR_DELETE.equals(byId.getStatus())){//账号状态为-1 则禁用失败
            throw new RuntimeException("账号已删除无法禁用");
        }
        if (BillConstants.ACCOUNT_SUBSCRIBER_BEHAVIOUR_FREEZE.equals(byId.getStatus())){
            throw new RuntimeException("账号已禁用请勿重复操作");
        }
        if ("admin".equals(byId.getLoginName())&&"系统管理员".equals(byId.getName())){
            throw new RuntimeException("系统管理员账号无法被冻结");
        }
        SysUser u =new SysUser();
        u.setId(user.getId());//用户id
        u.setStatus(BillConstants.ACCOUNT_SUBSCRIBER_BEHAVIOUR_FREEZE);//账号状态
        return updateById(u);
    }
    //删除账号
    @Override
    public boolean updateStatus(BaseDelVo vo) throws RuntimeException {
        boolean flag=false;
        sysUserMapper.updateStatus(vo.getIds());
        //删除关联信息
        sysUserMapper.deleteProjectUser(vo.getIds());
        flag=true;
        return flag;
    }

    @Override
    public boolean startStatus(SysEditVo user) {
        if (null==user.getId()){
            throw new RuntimeException("禁用账号失败");
        }
        SysUser byId = getById(user.getId());//查询远账号是否被删除
        if (BillConstants.ACCOUNT_SUBSCRIBER_BEHAVIOUR_DELETE.equals(byId.getStatus())){//账号状态为-1 则禁用失败
            throw new RuntimeException("账号已删除无法禁用");
        }
        if (BillConstants.ACCOUNT_SUBSCRIBER_BEHAVIOUR_START.equals(byId.getStatus())){
            throw new RuntimeException("账号已是启用状态,请勿重复操作");
        }
        SysUser u =new SysUser();
        u.setId(user.getId());//用户id
        u.setStatus(BillConstants.ACCOUNT_SUBSCRIBER_BEHAVIOUR_START);//账号状态
        return updateById(u);
    }


    //递归查找子菜单
    private List<SysRes> getChild(Long id,List<SysRes> list){
        List<SysRes> childList = new ArrayList<SysRes>();
        for(SysRes r:list){
            if(r.getPid().equals(id)){
                childList.add(r);
            }
        }
        for(SysRes r:childList){
            r.setChildRes(getChild(r.getId(),list));
        }
        if(childList.size()==0){
            return null;
        }
        return childList;
    }
}
